package com.general.framework.cc.thread;

import java.util.ArrayList;
import java.util.List;

public class UnSafeArrayList {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                // 线程不安全
                list.add(Thread.currentThread().getName());
                // 线程安全的做法
                // synchronized (list){
                //     list.add(Thread.currentThread().getName());
                // }
                System.out.println(list);
            },String.valueOf(i)).start();
        }

        // System.out.println(list.size());
    }
}
/*
这也是一种线程安全的做法
 CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
        for (int i = 0; i < 5000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        Thread.sleep(3000);
        System.out.println(list.size());
*/
/*
4579

Process finished with exit code 0
*/
